<script lang="ts" setup>
import { dataScope, deptTreeSelect, getRole } from '@/api/system/role'
import type { DataSopeParams } from '@/api/system/role/type'
import type { TreeInstance } from 'element-plus'

const dataScopeDialogVisible = ref(false)
const loading = ref(false)
const formLoading = ref(false)
const btnLoading = computed(() => loading.value || formLoading.value)
const dataScopeDialogForm = ref<DataSopeParams>({
	roleName: '',
	roleKey: '',
	dataScope: 0,
	menuCheckStrictly: true,
	deptCheckStrictly: false,
	id: 0,
	deptIds: []
})
const dataScopeDialogDeptTree = ref([
	{
		value: 1,
		label: '全部数据权限'
	},
	{
		value: 2,
		label: '自定数据权限'
	},
	{
		value: 3,
		label: '本部门数据权限'
	},
	{
		value: 4,
		label: '本部门及以下数据权限'
	},
	{
		value: 5,
		label: '仅本人数据权限'
	}
])
const deptExpand = ref(true)
const deptOptions = ref<any[]>([])
const deptNodeAll = ref(false)
const deptRef = ref<TreeInstance | null>(null)

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value: boolean | string | number) {
	if (deptRef.value) {
		deptRef.value.setCheckedNodes(value ? deptOptions.value : [])
	}
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value: boolean | string | number) {
	let treeList = deptOptions.value
	for (let i = 0; i < treeList.length; i++) {
		if (deptRef.value) {
			deptRef.value!.store.nodesMap[treeList[i].id].expanded = !!value
		}
	}
}
/** 树权限（父子联动） */
function handleCheckedTreeConnect(value: boolean | string | number) {
	dataScopeDialogForm.value.deptCheckStrictly = !!value
}
/** 所有部门节点数据 */
function getDeptAllCheckedKeys() {
	if (!deptRef.value) return
	// 目前被选中的部门节点
	let checkedKeys = deptRef.value.getCheckedKeys()
	// 半选中的部门节点
	let halfCheckedKeys = deptRef.value.getHalfCheckedKeys()
	checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
	return checkedKeys
}
function dataScopeDialogSubmit() {
	const params = {
		...dataScopeDialogForm.value,
		deptIds: getDeptAllCheckedKeys() as number[]
	}
	dataScope(params).then(() => {
		ElMessage.success('修改成功')
		dataScopeDialogClose()
	})
}

const init = async (roleId: number) => {
	dataScopeDialogVisible.value = true
	try {
		formLoading.value = true
		const res = await deptTreeSelect(roleId)
		const { checkedKeys, depts } = res.data
		deptOptions.value = depts
		const { data } = await getRole(roleId)
		dataScopeDialogForm.value.roleName = data.roleName
		dataScopeDialogForm.value.roleKey = data.roleKey
		dataScopeDialogForm.value.dataScope = data.dataScope
		dataScopeDialogForm.value.id = data.id

		if (deptRef.value) {
			deptRef.value.setCheckedKeys(checkedKeys ?? [])
		}
	} finally {
		formLoading.value = false
	}
}
function dataScopeDialogClose() {
	dataScopeDialogVisible.value = false
}

defineExpose({
	init
})
</script>

<template>
	<ElDialog
		v-model="dataScopeDialogVisible"
		title="分配数据权限"
		width="800px"
		:close-on-click-modal="false"
		@close="dataScopeDialogClose"
	>
		<ElForm
			v-loading="formLoading"
			:model="dataScopeDialogForm"
		>
			<ElFormItem
				label="角色名称"
				prop="roleName"
			>
				<ElInput
					v-model="dataScopeDialogForm.roleName"
					disabled
				/>
			</ElFormItem>
			<ElFormItem
				label="权限字符"
				prop="roleKey"
			>
				<ElInput
					v-model="dataScopeDialogForm.roleKey"
					disabled
				/>
			</ElFormItem>
			<ElFormItem
				label="权限范围"
				prop="dataScope"
			>
				<ElSelect v-model="dataScopeDialogForm.dataScope">
					<ElOption
						v-for="item in dataScopeDialogDeptTree"
						:key="item.value"
						:label="item.label"
						:value="item.value"
					/>
				</ElSelect>
			</ElFormItem>
			<ElFormItem
				v-show="dataScopeDialogForm.dataScope === 2"
				label="数据权限"
			>
				<div>
					<el-checkbox
						v-model="deptExpand"
						@change="handleCheckedTreeExpand($event)"
					>
						展开/折叠
					</el-checkbox>
					<el-checkbox
						v-model="deptNodeAll"
						@change="handleCheckedTreeNodeAll"
					>
						全选/全不选
					</el-checkbox>
					<el-checkbox
						v-model="dataScopeDialogForm.deptCheckStrictly"
						@change="handleCheckedTreeConnect($event)"
					>
						父子联动
					</el-checkbox>
					<el-tree
						ref="deptRef"
						class="tree-border"
						:data="deptOptions"
						show-checkbox
						default-expand-all
						node-key="id"
						:check-strictly="!dataScopeDialogForm.deptCheckStrictly"
						empty-text="加载中，请稍候"
						:props="{ label: 'label', children: 'children' }"
					/>
				</div>
			</ElFormItem>
		</ElForm>
		<template #footer>
			<el-button @click="dataScopeDialogClose">取消</el-button>
			<el-button
				type="primary"
				:loading="btnLoading"
				@click="dataScopeDialogSubmit"
			>
				确定
			</el-button>
		</template>
	</ElDialog>
</template>

<style lang="scss" scoped></style>
